<template>
  <view class="container">
    <!-- 状态栏占位 -->
    <!-- #ifdef MP-WEIXIN -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>
    <!-- #endif -->
    
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <image src="/static/Images/notice/Fanhui.png" class="back-icon"></image>
      </view>
      <view class="title">交易通知</view>
      <view class="placeholder"></view>
    </view>
    <!-- 顶部标签切换 -->
    <view class="tab-container">
      <view class="tab-item" :class="{ active: activeTab === 'buy' }" @click="switchTab('buy')">
        <text class="tab-text">我买的</text>
      </view>
      <view class="tab-item" :class="{ active: activeTab === 'sell' }" @click="switchTab('sell')">
        <text class="tab-text">我卖的</text>
      </view>
    </view>

    <!-- 交易通知列表 -->
    <view class="trade-list">
      <!-- 我买的订单 -->
      <view v-if="activeTab === 'buy'" class="order-section">
        <view v-if="buyOrders.length === 0" class="empty-state">
          <image class="empty-icon" src="/static/Images/common/empty.png" mode="aspectFit"></image>
          <text class="empty-text">暂无购买订单</text>
        </view>
        <view v-else>
          <view v-for="order in buyOrders" :key="order.id" class="order-item" @click="viewOrderDetail(order)">
            <view class="order-header">
              <view class="order-info">
                <text class="order-number">订单号：{{ order.orderNo }}</text>
                <view class="order-status" :class="getStatusClass(order.status)">
                  <image class="notice-icon" src="/static/Images/common/Xiaoxitongzhi.png" mode="aspectFit"></image>
                  <text class="status-text">您的订单在{{ formatTime(order.updateTime) }}更新为{{ getStatusText(order.status) }}</text>
                </view>
              </view>
            </view>
            <view class="notice-content">
              <view class="notice-row">
                <text class="notice-message">订单最新状态为：{{ getStatusText(order.status) }}</text>
                <text class="order-time">{{ formatTime(order.updateTime) }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 我卖的订单 -->
      <view v-if="activeTab === 'sell'" class="order-section">
        <view v-if="sellOrders.length === 0" class="empty-state">
          <image class="empty-icon" src="/static/Images/common/empty.png" mode="aspectFit"></image>
          <text class="empty-text">暂无销售订单</text>
        </view>
        <view v-else>
          <view v-for="order in sellOrders" :key="order.id" class="order-item" @click="viewOrderDetail(order)">
            <view class="order-header">
              <view class="order-info">
                <text class="order-number">订单号：{{ order.orderNo }}</text>
                <view class="order-status" :class="getStatusClass(order.status)">
                  <image class="notice-icon" src="/static/Images/common/Xiaoxitongzhi.png" mode="aspectFit"></image>
                  <text class="status-text">{{ getStatusText(order.status) }}</text>
                </view>
              </view>
            </view>
            <view class="notice-content">
              <view class="notice-row">
                <text class="notice-message">订单最新状态为：{{ getStatusText(order.status) }}</text>
                <text class="order-time">{{ formatTime(order.updateTime) }}</text>
              </view>
              <text class="buyer-info">买家：{{ order.buyerName }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { goodsApi, orderApi } from '@/utils/api';
import { userStorage } from '@/utils/storage';

// 响应式数据
const statusBarHeight = ref(0); // 状态栏高度
const activeTab = ref('buy');
const buyOrders = ref([]);
const sellOrders = ref([]);
const loading = ref(false);

// 切换标签
const switchTab = (tab) => {
  activeTab.value = tab;
  if (tab === 'buy') {
    loadBuyOrders();
  } else {
    loadSellOrders();
  }
};

// 加载购买订单
const loadBuyOrders = async () => {
  try {
    loading.value = true;
    // 使用现有的用户订单列表接口，type=0表示购买订单
    const response = await goodsApi.userOrderList({ status: 0, type: 0, page: 1, size: 20 });
    if (response.data && Array.isArray(response.data)) {
      buyOrders.value = response.data.map(item => ({
        id: item.id || item.order_id,
        orderNo: item.order_no || item.orderNo || item.id,
        status: item.status,
        updateTime: item.end_time || item.create_time,
        rawData: item
      }));
    }
  } catch (error) {
    console.error('加载购买订单失败:', error);
    uni.showToast({ title: error.message || '加载失败', icon: 'none' });
  } finally {
    loading.value = false;
  }
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '已取消',
    1: '待支付',
    2: '待发货',
    3: '待收货',
    4: '已完成',
    9: '退款/售后',
    6: '已评价',
  };
  return statusMap[status] || '未知状态';
};

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    0: '#666666',
    1: '#FF6B35',
    2: '#2196F3',
    3: '#9C27B0',
    4: '#4CAF50',
    6: '#FF9800', 
    9: '#FF5722',
  };
  return colorMap[status] || '#666666';
};

// 加载销售订单
const loadSellOrders = async () => {
  try {
    loading.value = true;
    // 使用现有的抢单订单列表接口，获取销售相关订单
    const response = await goodsApi.findGrabOrderByUser({ bus_status: 0, type: 0, page: 1, size: 20 });
    if (response.data && Array.isArray(response.data)) {
      sellOrders.value = response.data.map(item => ({
        id: item.id || item.order_id,
        orderNo: item.order_no || item.orderNo || item.id,
        status: item.status || item.order_status || 0,
        updateTime: item.update_time || item.created_at || item.create_time,
        buyerName: item.buyer_name || item.user_name || '匿名用户',
        rawData: item
      }));
    }
  } catch (error) {
    console.error('加载销售订单失败:', error);
    uni.showToast({ title: error.message || '加载失败', icon: 'none' });
  } finally {
    loading.value = false;
  }
};

// 获取订单状态样式类
const getStatusClass = (status) => {
  const statusMap = {
    'pending': 'status-pending',
    'paid': 'status-paid',
    'shipped': 'status-shipped',
    'completed': 'status-completed',
    'cancelled': 'status-cancelled'
  };
  return statusMap[status] || 'status-default';
};

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 查看通知详情
const viewOrderDetail = (order) => {
  // 标记通知为已读
  markAsRead(order.id);
  // 跳转到订单详情页面
  uni.navigateTo({
    url: `/pages/order/orderdetail?id=${order.id}`
  });
};

// 标记通知为已读
const markAsRead = async (noticeId) => {
  try {
    await orderApi.markTradeNoticeRead(noticeId);
  } catch (error) {
    console.error('标记已读失败:', error);
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateTo({
    url: '/pages/notice/index'
  });
};

// 页面加载
onLoad(() => {
  // #ifdef MP-WEIXIN
  // 获取系统信息
  const systemInfo = uni.getSystemInfoSync()
  // 获取胶囊按钮信息
  const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  // 计算状态栏高度
  statusBarHeight.value = systemInfo.statusBarHeight + (menuButtonInfo.top - systemInfo.statusBarHeight) + menuButtonInfo.height + 10
  // #endif
});

onMounted(() => {
  loadBuyOrders();
});
</script>

<style lang="scss" scoped>
/* 状态栏样式 */
.status-bar {
  width: 100%;
  background: linear-gradient(180deg, #FF7B80 0%, rgba(244,234,234,0) 100%);
}

/* 容器 */
.container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 头部导航栏 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 88rpx 32rpx 32rpx 32rpx;
  background-color: #ffffff;
  position: relative;
}

.back-btn {
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

.title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333333;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.placeholder {
  width: 48rpx;
  height: 48rpx;
}

/* 标签容器 */
.tab-container {
  display: flex;
  background-color: #fff;
}

.tab-item {
  flex: 1;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 12rpx;
  transition: all 0.3s ease;
}

.tab-item.active {
  background-color: #ff4757;
  box-shadow: 0 4rpx 8rpx rgba(255, 71, 87, 0.3);
}

.tab-text {
  font-size: 32rpx;
  font-weight: 500;
  color: #666;
  transition: color 0.3s ease;
}

.tab-item.active .tab-text {
  color: #fff;
}

/* 交易列表 */
.trade-list {
  padding: 0 20rpx;
}

.order-section {
  margin-bottom: 40rpx;
  margin-top: 20rpx;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
}

.empty-icon {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 40rpx;
  opacity: 0.6;
}

.empty-text {
  font-size: 32rpx;
  color: #999;
}

/* 订单项 */
.order-item {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  transition: transform 0.2s ease;
}

.order-item:active {
  transform: scale(0.98);
}

/* 订单头部 */
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24rpx;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.order-number {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.order-status {
  display: flex;
  align-items: center;
  padding: 16rpx 0rpx;
  border-radius: 20rpx;
  align-self: flex-start;
}

.notice-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 8rpx;
}

.status-text {
  font-size: 24rpx;
  font-weight: 500;
}

.status-pending {
  background-color: #fff3cd;
  color: #856404;
}

.status-paid {
  background-color: #d4edda;
  color: #155724;
}

.status-shipped {
  background-color: #cce7ff;
  color: #004085;
}

.status-completed {
  background-color: #d1ecf1;
  color: #0c5460;
}

.status-cancelled {
  background-color: #f8d7da;
  color: #721c24;
}

.order-time {
  font-size: 24rpx;
  color: #999;
  white-space: nowrap;
}

/* 通知内容 */
.notice-content {
  margin-bottom: 16rpx;
}

.notice-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12rpx;
}

.notice-message {
  font-size: 30rpx;
  color: #333;
  line-height: 1.5;
  flex: 1;
  margin-right: 20rpx;
}

.buyer-info {
  font-size: 26rpx;
  color: #666;
}
</style>